from openai import OpenAI

from core.xiaoyu_qqbot._dto import AgentUsePlate


class AIAgentByOpenAI:
    def __init__(
            self,
            agent_use_plate: AgentUsePlate(),
            api_key,
            use_model: str = None
    ):
        self._ai_agent = None
        self.use_model = use_model
        self._message_history = []  # 添加消息历史列表
        if agent_use_plate == AgentUsePlate.DeepSeek:
            self._ai_agent = OpenAI(api_key=api_key, base_url="https://api.deepseek.com")
            self.use_model = 'deepseek-chat'
        elif agent_use_plate == AgentUsePlate.Ollama:
            self._ai_agent = OpenAI(api_key='ollama', base_url="http://localhost:11434/v1/")
            if use_model is None:
                self.use_model = 'deepseek-r1:8b'
                self.use_model = 'llama3.2:latest'
        else:
            print('目前不支持该平台请求方式，程序退出')
            exit()

    def chat(self, message: str, max_history: int = 10) -> str:
        """
        进行带上下文的对话
        
        Args:
            use_model: 使用的模型名称
            message: 用户输入的消息
            max_history: 保留的最大历史消息数量
        
        Returns:
            str: AI的回复内容
        """
        # 添加用户消息到历史
        self._message_history.append({"role": "user", "content": message})

        # 保持历史消息在最大数量限制内
        if len(self._message_history) > max_history * 2:  # *2是因为每轮对话包含用户和助手各一条消息
            self._message_history = self._message_history[-max_history * 2:]

        try:
            # 创建对话请求
            response = self._ai_agent.chat.completions.create(
                model=self.use_model,
                messages=[
                    {"role": "system", "content": "you are a helpful assistant"},
                    *self._message_history
                ],
                stream=False
            )

            # 获取AI回复
            ai_response = response.choices[0].message.content

            # 将AI回复添加到历史
            self._message_history.append({"role": "assistant", "content": ai_response})

            return ai_response

        except Exception as e:
            print(f"聊天过程中发生错误: {str(e)}")
            return f"抱歉，发生了错误: {str(e)}"

    def clear_history(self):
        """清除对话历史"""
        self._message_history = []

    def function_calling(self):
        # 通过模型执行一些外部方法
        # 文档 https://www.cnblogs.com/mingupupu/p/18385274
        ...
    def other(self):
        ...
